package cn.tedu.sp06zuul.filter;

import cn.tedu.web.util.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {




        // 先获取当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        // 当前请求，调用的服务id
        String serviceId = (String)
                ctx.get(FilterConstants.SERVICE_ID_KEY);// "serviceId"
        // 调用的是否是 item-service
        return "item-service".equals(serviceId);

    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        /*接受token参数*/
        String token = request.getParameter("token");
        if(StringUtils.isBlank(token)){
            /*阻止继续调用*/
            ctx.setSendZuulResponse(false);
            /*直接返回相应*/
            // JsonResult --- {code:1,msg:xxx,data:null}
            ctx.addZuulResponseHeader(
                    "Contend-Type","application/json;charset=utf-8"

            );
            ctx.setResponseBody(JsonResult.err().code(400).msg("Not login! 未登录！").toString());
        }
        return null;// 当前 zuul 版本中，这个返回值没有使用
    }
}
